package com.zb.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 *
 */
//@Component
public class PowerFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("进入权限拦截器......17002");
        //获取用户访问接口路径
        String path = exchange.getRequest().getURI().getPath().toString();
        //需要放行的接口
        if (path.startsWith("/api/auth/login")) {
            System.out.println("放行接口.....");
            return chain.filter(exchange);
        }
        //获取请求头中的token
        String token = exchange.getRequest().getHeaders().getFirst("token");
        System.out.println("header:" + token);
        //请求头中不存在
        if (StringUtils.isEmpty(token)) {
            //才从请求参数中获取
            token = exchange.getRequest().getQueryParams().getFirst("token");
        }
        //都不存在，返回没有登录的状态码，并不执行下一步的请求
        if (StringUtils.isEmpty(token)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        //将令牌从新设置bearer的写法传输到微服务
        exchange.getRequest().mutate().header("Authorization", "bearer " + token);
        return chain.filter(exchange);

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
